<?php

/**
 * WK  购买羊
 * ============================================================================
 * * 版权所有 2005-2012 QQ 80342014，并保留所有权利。
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: liubo $
 * $Id: index.php 17217 2011-01-19 06:29:08Z liubo $
*/

define('IN_ECS', true);
require(dirname(__FILE__) . '/includes/init.php');

assign_template();


$action  = isset($_REQUEST['act']) ? trim($_REQUEST['act']) : 'list';

$position = assign_ur_here();
$smarty->assign('page_title',      $position['title']);    // 页面标题
$smarty->assign('ur_here',         $position['ur_here']);  // 当前位置
$smarty->assign('action',     $action);

/*-------------------------------------*/
//-  异步加载列表
/*-------------------------------------*/
if($action == 'ajaxlist'){
/* 获得当前页码 */
$page   = !empty($_REQUEST['page'])  && intval($_REQUEST['page'])  > 0 ? intval($_REQUEST['page'])  : 1;	
	/* 获得 羊 */
    $size   =  intval($_GET['size']) ? intval($_GET['size'])  : 4;
    $count  = get_sheep_count();
    $pages  = ($count > 0) ? ceil($count / $size) : 1;
	if ($page > $pages)
    {
        $list = array();
    }else{
		$list = get_sheep_list( $page, $size );
	} 
 
	$data = array();
	$data['list'] = $list;
	$data['lengths'] = count($list);
	$data['page'] = $page;
	$data['pages'] = $pages;
	$data['size'] = $size;
	die(json_encode($data));
}
/*-------------------------------------*/
//-  异步计算价格
/*-------------------------------------*/
elseif($action == 'ajaxprice' ){
	
	$data = array('error'=>0,'msg'=>'','content'=>'');
	$id  = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : '';
	$number  = isset($_REQUEST['number']) ? intval($_REQUEST['number']) : '1';
	if($id <= 0){
		$data['error'] = 1;
		$data['msg'] = '非法入口，没有有效的ID信息';
		die(json_encode($data));
	}
	$sheep = get_sheep_details($id);
	if(empty($sheep)){
		$data['error'] = 1;
		$data['msg'] = '没有该羊的信息,重新选择';
		die(json_encode($data));
	}
	$data['content'] = '<span>总价：</span><span class="gan-price">¥</span>'. $number * $sheep['price'];
	die(json_encode($data));
}
/*-------------------------------------*/
//-  异步购买  购买立即锁定
/*-------------------------------------*/
elseif($action == 'ajaxbuy' ){
	
	$data = array('error'=>0,'msg'=>'','content'=>'');
	$id  = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : '';
	$number  = isset($_REQUEST['number']) ? intval($_REQUEST['number']) : '1';
	if($_SESSION['user_id'] <= 0){
		$data['error'] = 1;
		$data['msg'] = '没有登录,请登录后在来购买';
		die(json_encode($data));
	}
	
	if($id <= 0){
		$data['error'] = 1;
		$data['msg'] = '非法入口，没有有效的ID信息';
		die(json_encode($data));
	}
	$sheep = get_sheep_details($id);
	if(empty($sheep)){
		$data['error'] = 1;
		$data['msg'] = '没有该羊的信息,重新选择';
		die(json_encode($data));
	}
	/* 清空已经到期的没有付款的羊 */
	delect_sheep_cart(array($id));
	
	/* 验证 购买的数量有多少  羊 购物车 */
	$sheep_cart_count = sheep_cart_count($id);
	/* 计算最多可以购买多少  */
	$kegoumai = $sheep['sy_number'] - $sheep_cart_count;
	if($number > $kegoumai){
		$data['error'] = 1;
		$data['msg'] = '数量没有那么多，请重新选择';
		die(json_encode($data));
	}
	/* 加入购买列表  */
	$parent = array(
        'user_id'       => $_SESSION['user_id'],
        'sheep_id'   	=> $id,
        'sheep_number'  => $number,
        'add_time'      =>  gmtime() ,
        'end_time'      =>  gmtime() + 60 * $GLOBALS['_CFG']['locking_time'], /* 五分钟没有支付就清空 */
        // 'end_time'      =>  gmtime() + 60 * 155, /* 五分钟没有支付就清空 */
        'sheep_price'      =>  $number * $sheep['price'] , 
    );
	$GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('sheep_cart'), $parent, 'INSERT');
	$data['error'] = 0;
	$data['msg'] = '购买成功';
	die(json_encode($data));
}
/*-------------------------------------*/
//-  异步验证 是否银行卡认证支付
/*-------------------------------------*/
elseif($action == 'ajaxpay_code' ){
	
	$code = isset($_GET['code']) ? trim($_GET['code']) : 'bank';
	$data = array('error'=>0,'msg'=>'','content'=>'');
	if($_SESSION['user_id'] <= 0 || empty($_SESSION['user_name'])){
		$data['error'] = 1;
		$data['msg'] = '登录失效,请重新登录';
		die(json_encode($data));
	}else{
		$data['error'] = 2;
		$data['msg'] = '登录失效,请重新登录';
		die(json_encode($data));
	}
	
	
	echo "<pre>"; print_r($_GET);
	echo "<pre>"; print_r($_SESSION['user_id']);
	die('ddd');
}	
	
elseif($action == 'ajax_sheep_details'){
	$id  = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : '1';
	$data = array('error'=>0,'msg'=>'','content'=>'');
	 
	/* 清空已经到期的没有付款的羊 */
	delect_sheep_cart(array($id));
	$sheep = get_sheep_details($id);
	$smarty->assign('gmtimes',        gmtime());
	$smarty->assign('sheep',        $sheep);
	$smarty->assign('user_id',        $_SESSION['user_id']);
	$smarty->assign('id',        $id);
	/* 自己购买羊的 数据  */
	$thissheep = thissheep($_SESSION['user_id'],$id);
	$smarty->assign('thissheep',        $thissheep);
	
	
	/* 处理了没有支付的订单  清空 并返回 库存 */
	weizhfu_order();
	/* 获取自己没有支付的订单 */
	$order = user_weizhfu_order($_SESSION['user_id']);
	$smarty->assign('order',        $order);
	
	$data['content'] = $smarty->fetch('library/sheep_details.lbi');
	die(json_encode($data));
	
}
	
/*  列表 */
if($action == 'order'){
	
	$order_id  = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : '';
	weizhfu_order();
	$smarty->assign('acts',        'sheep');
	$smarty->assign('page_title',        '羊只列表');

	$order = get_sheep_info($order_id);
   include_once(ROOT_PATH .'includes/lib_clips.php');
	
	$smarty->assign('info',        get_user_default($_SESSION['user_id']));
	$payment_list = available_payment_list(1);
	$is_weixin = 0;
	if(strpos( $_SERVER['HTTP_USER_AGENT'],'MicroMessenger') > 0 ){
		$is_weixin = 1;
	}
	$payment_lists = array();
	if($payment_list){
		foreach($payment_list as $k => $v){
			/* 不是微信就移除微信支付 */
			if($is_weixin != 1 && $v['pay_code'] == 'wxpay'){
				continue;
			}
			$payment_lists[] =  $v;
		}
	}
 
	$smarty->assign('payment_list',        $payment_lists);
	if($order['pay_time'] > 0){
		show_message("该订单已支付", "返回上一页", 'sheep.php', 'error');
	}
	if($order['user_id'] != $_SESSION['user_id']){
		show_message("不能操作别人的订单", "返回上一页", 'sheep.php', 'error');
	}
	
	$smarty->assign('order',        $order);
	$smarty->display('sheep_order.dwt');
}

/*  列表 */
if($action == 'list'){
	$smarty->assign('acts',        'sheep');
	$smarty->assign('page_title',        '羊只列表');

	/* 处理了没有支付的订单  清空 并返回 库存 */
	 weizhfu_order();
	
	/* 记录 羊被购买的字段 */
		// updata_sheep($sheep['sheep_id'],$sheep_cart['sheep_number']);
	
	
	$smarty->display('sheep_list.dwt');
}
/*  详情 */
elseif( $action== 'details'){
	
	$id  = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : '';
	if($id <= 0){
		show_message("非法入口，没有有效的ID信息", "返回上一页", 'sheep.php', 'error');
	}
	/* 清空已经到期的没有付款的羊 */
	delect_sheep_cart(array($id));
	$sheep = get_sheep_details($id);
	
	
	
	if(empty($sheep)){
		show_message("没有该羊的信息,重新选择", "返回上一页", 'sheep.php', 'error');
	}
	/* 排行榜 */
	$xiangxiphb = phb($id,1);
	$benqiphb = phb($id,2);
	$smarty->assign('xiangxiphb',        $xiangxiphb);
	$smarty->assign('benqiphb',        $benqiphb);


	
	$smarty->assign('acts',        'sheep');
	$smarty->assign('page_title',        '羊只详情');
	$smarty->assign('id',        $id);
	$smarty->assign('gmtimes',        gmtime());
	$smarty->assign('sheep',        $sheep);
	$smarty->assign('user_id',        $_SESSION['user_id']);
	
	
	/* 处理了没有支付的订单  清空 并返回 库存 */
	weizhfu_order();
	/* 获取自己没有支付的订单 */
	$order = user_weizhfu_order($_SESSION['user_id']);
	$smarty->assign('order',        $order);
 
	
	/* 自己购买羊的 数据  */
	$thissheep = thissheep($_SESSION['user_id'],$id);
	$smarty->assign('thissheep',        $thissheep);
	
	
	$smarty->display('sheep_details.dwt');
}

/*  详情 */
elseif( $action== 'buy'){
	
	if($_SESSION['user_id'] <= 0){
		show_message("登录超时", "重新登录", 'user.php', 'error');
	}
	/* 处理了没有支付的订单  清空 并返回 库存 */
	weizhfu_order();
	delect_sheep_cart_quanbu();
	$sheep_cart = get_sheep_cart_list($_SESSION['user_id']);
	if(empty($sheep_cart['list']) || empty($sheep_cart['id']) ||  empty($sheep_cart['sheep_price'])){
		show_message("订单超时", "重新购买", 'sheep.php', 'error');
	}
 
	$smarty->assign('sheep_cart',        $sheep_cart);
    include_once(ROOT_PATH .'includes/lib_clips.php');
	
	$smarty->assign('info',        get_user_default($_SESSION['user_id']));
	
	$payment_list = available_payment_list(1);
	$is_weixin = 0;
	if(strpos( $_SERVER['HTTP_USER_AGENT'],'MicroMessenger') > 0 ){
		$is_weixin = 1;
	}
	$payment_lists = array();
	if($payment_list){
		foreach($payment_list as $k => $v){
			/* 不是微信就移除微信支付 */
			if($is_weixin != 1 && $v['pay_code'] == 'wxpay'){
				continue;
			}
			$payment_lists[] =  $v;
		}
	}
 
	$smarty->assign('payment_list',        $payment_lists);
	

	
	$smarty->display('sheep_buy.dwt');
}
/*  支付 */
elseif($action== 'done'){
	include_once('includes/cls_json.php');
	include_once(ROOT_PATH .'includes/lib_clips.php');
	include_once('includes/lib_payment.php');
	$user = get_user_default($_SESSION['user_id']);
    $_POST['arr']=strip_tags(urldecode($_POST['arr']));
    $_POST['arr'] = json_str_iconv($_POST['arr']);
	$json  = new JSON;
	$arr = $json->decode($_POST['arr']);
	$result = array('error' => 0, 'message' => '', 'content' => '', 'goods_id' => '');
	
	$pays = $GLOBALS['db']->getRow("select * from ". $GLOBALS['ecs']->table('payment') ." where pay_code = '". $arr->code ."'");
	if(empty($pays)){
		$result['error'] = 2;
		$result['message'] = "没有该支付方式，请联系管理员";
		die($json->encode($result));
	}
 

	if($_SESSION['user_id'] <= 0){
		$result['error'] = 1;
		$result['message'] = "用户登录超时";
        die($json->encode($result));
	}
	delect_sheep_cart_quanbu();
	$sheep_cart = get_sheep_cart_list($_SESSION['user_id']);
	if($sheep_cart['id'] <= 0 || empty($sheep_cart['sheep_price'])){
		$result['error'] = 2;
		$result['message'] = "没有该订单或订单超时";
        die($json->encode($result));
	}
	/* 如果是是余额支付 */

	if($arr->code  == 'balance' && !empty($arr->pay_password) && $arr->cart_id > 0 ){
		/* 验证 密码是否正确 */
		if($user['pay_password'] != $arr->pay_password ||  empty($arr->pay_password)){
			$result['error'] = 2;
			$result['message'] = "支付密码不对,重新输入";
			die($json->encode($result));
		}
		/* 验证 当前用户钱是否够 */
		if($user['user_money'] < $sheep_cart['sheep_price']){
			$result['error'] = 2;
			$result['message'] = "青山羊币不足,请充值或者用认证银行卡支付";
			die($json->encode($result));
		}
	}
	
	/* wk  如果是微信支付 */
	if($arr->code  == 'wxpay'){
		$return_url = 'http://' . $_SERVER['HTTP_HOST'].'/respond.php&code=wxpay';
		$payment = unserialize($pays['pay_config']);
		define (WXAPPID, $payment['0']['value']); // appid
		define (WXAPPSECRET, $payment['1']['value']); // appSecret
		define (WXMCHID, $payment['2']['value']);
		define (WXKEY, $payment['3']['value']); // 通加密串
		define (NOTIFY_URL, $return_url); // 成功回调url
		include_once("includes/modules/payment/WxPayPubHelper/WxPayPubHelper.php");
		$jsApi = new JsApi_pub();
		$selfUrl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'];
		if($_SESSION['user_id']){
			$openid = $GLOBALS['db']->getOne("select wxid from ". $GLOBALS['ecs']->table('users') ." where user_id ='{$_SESSION['user_id']}'");
		}
		$openid = $openid ? $openid : $_SESSION['openids'];
		if(empty($openid)){
			$result['error'] = 0;
			$result['message'] = "当前用户没有绑定微信,请在微信端打开进行支付";
			die($json->encode($result));
		}
	}

	$sheep = get_sheep_details($sheep_cart['list']['sheep_id']);
	/* 购买羊支付  余额 */
	$time = gmtime();
	$dangqian = local_date($GLOBALS['_CFG']['time_format'], $time); 
	
	/* 默认时间 */
	$bonus_time_yue = $dangqian;
	$bonus_time = $time;
	$bonus_time_done = $time;
	if($sheep['cycle'] > 0){
		$bonus_time_yue = date("Y-m-d H:i:s", strtotime("+1 months", strtotime($dangqian)));
		$bonus_time = strtotime(date ($bonus_time_yue));
		$bonus_time_done_yue = date("Y-m-d H:i:s", strtotime("+".$sheep['cycle']." months", strtotime($dangqian)));
		$bonus_time_done = strtotime(date ($bonus_time_done_yue));
	}
	$userset = get_user_set($_SESSION['user_id']);
	$order = array(
		'sheep_id' => $sheep_cart['list']['sheep_id'],/* 羊编号 */
		'user_id' => isset($_SESSION['user_id']) ? $_SESSION['user_id'] : $sheep_cart['list']['user_id'],/* 用户编号 */
		'sheep_number' => $sheep_cart['sheep_number'],/* 数量  */
		'sheep_price' => $sheep_cart['sheep_price'],/* 价格  */
		'add_time' => $time,/* 时间  */
		'pay_type' => $arr->code,/* 时间  */
		'parent_id' => $userset['parent_id'],/* 上级id  */
		'bonus' => round($sheep['bonus'] / 12,3),/* 分红比例  */
		'cycle' => $sheep['cycle'],/* 分红月  */
		'bonus_time' => $bonus_time,/* 下一次分红时间  当前时间 加一个月  */
		'bonus_time_yue' => $bonus_time_yue,/* 下一次分红时间  当前时间 加一个月  */
		'bonus_time_done' => $bonus_time_done,/* 最终分红时间  */
		'bonus_time_done_yue' => $bonus_time_done_yue,/* 最终分红时间  */
	);
	
	
	/*  余额支付  处理后续操作 */
	if($arr->code  == 'balance'){
		$GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('sheep_order'), $order, 'INSERT');
		$order_id = $db->insert_id();
		/* 清空表 */
		del_sheep_cart($sheep_cart['id']);
		/* 购买通知  */
		$order['order_id'] = $order_id;
		if($userset['wxid'] && $userset['yz_gm_msg'] == 1){
			wx_msg($userset['wxid'],3,$order);
		}
		
		/* 给上级 发送信息 */
		if($userset['parent_id'] > 0){
			$u_set = get_user_set($userset['parent_id']);
			if($u_set['wxid'] && $userset['tg_gm_msg'] == 1){
				wx_msg($u_set['wxid'],5,$order);
			}
		}
		$sql = "UPDATE ". $ecs->table('sheep_order') ." SET pay_time = '". gmtime() ."' , state = '2',pay_type = 'balance' WHERE order_id= '". $order_id ."'";
        $db->query($sql);
	 
		
	
		/* 根据订单ID 生成排队分成队列 */
		bonus_queue($order_id);
		/* 扣钱 */
		$text = "购买羊支出青山羊币：".$sheep_cart['sheep_price'];
		log_account_change($_SESSION['user_id'], -$sheep_cart['sheep_price'], 0, 0, 0, $text , ACT_GMY); // 购买羊
		
		/* 清空表 */
		del_sheep_cart($sheep_cart['id']);
		
		/* 记录 羊被购买的字段 */
		updata_sheep($sheep['sheep_id'],$sheep_cart['sheep_number']);
		
		$result['order_id'] = $order_id;
		$result['error'] = 0;
		$result['message'] = "购买成功";
		die($json->encode($result));
	}

	/* 如果是其他支付 */
	if($arr->code  != 'balance' &&  !empty($arr->code) && $arr->code  != 'wxpay'){
		
		$payment = $GLOBALS['db']->getRow("select * from ". $GLOBALS['ecs']->table('payment') ." where pay_code = '". $arr->code ."'");
		if(empty($payment)){
			$result['error'] = 0;
			$result['message'] = "没有该支付方式，请联系管理员";
			die($json->encode($result));
		}
		$GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('sheep_order'), $order, 'INSERT');
		
		$order_id = $db->insert_id();
		
		/* 记录 羊被购买的字段 */
		updata_sheep($sheep['sheep_id'],$sheep_cart['sheep_number']);
		
		
		$order['order_id'] = $order_id;
		/* 清空表 */
		del_sheep_cart($sheep_cart['id']);
        include_once('includes/modules/payment/' . $payment['pay_code'] . '.php');
        $pay_obj    = new $payment['pay_code'];
		// $order['order_id'] = '1'; /* 后期用订单 id  */
		
		$order['order_amount'] = $order['sheep_price'];/* 总金额 */
		// $order['order_amount'] = '0.01';/* 总金额 */
		
		$order['log_id'] = insert_pay_log($order['order_id'], $order['order_amount'], PAY_YZGM); /* 羊只付款 */
		$order['order_sn'] = gmtime().'GMYZ';/* 回调准备才分 */
 
		
        $pay_online = $pay_obj->get_code($order, unserialize_config($payment['pay_config']));
        // $order['pay_desc'] = $payment['pay_desc'];
		// $smarty->assign('pay_online', $pay_online);
		$result['order_id'] = $order_id;
		$result['error'] = 10;
		$result['message'] = "支付按钮";
		$result['pay_online'] =  $pay_online;
		die($json->encode($result));
		
	}
	
	if($arr->code  == 'wxpay'){
		$GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('sheep_order'), $order, 'INSERT');
		$order_id = $db->insert_id();
		/* 记录 羊被购买的字段 */
		updata_sheep($sheep['sheep_id'],$sheep_cart['sheep_number']);
		/* 清空表 */
		del_sheep_cart($sheep_cart['id']);
			
		$unifiedOrder = new UnifiedOrder_pub();
		// 设置统一支付接口参数out_trade_no
		$unifiedOrder->setParameter ( "openid", $openid );
		$unifiedOrder->setParameter ( "body", 'GMYZ' );
		$unifiedOrder->setParameter ( "out_trade_no", $order_id ); // 商户订单号
		$unifiedOrder->setParameter ( "total_fee", $order['sheep_price'] * 100 ); // 总金额
		$unifiedOrder->setParameter ( "notify_url", NOTIFY_URL ); // 通知地址
		$unifiedOrder->setParameter ( "trade_type", "JSAPI" ); // 交易类型
	
		$prepay_id = $unifiedOrder->getPrepayId();
		$jsApi->setPrepayId($prepay_id);
		$obj['appId'] = $result['appId2'] = $payment['0']['value'];
		$obj['timeStamp'] = $result['timeStamp'] = time();
		$obj['nonceStr'] = $result['nonceStr2'] = $unifiedOrder->createNoncestr();
		$obj['package'] = $result['packages'] = "prepay_id=".$jsApi->prepay_id;
		$obj['signType'] = $result['signType2'] = 'MD5';
		$result['paySign2'] = $unifiedOrder->getSign($obj);
		$result['message'] = 'success';
		$result['order_id'] = $order_id;
		$result['error'] = 20;
		die($json->encode($result));

	}
	
	
	echo "ddd<pre>"; print_r($sheep_cart);
	echo "ddd<pre>"; print_r($arr);
	echo "<pre>"; print_r($_POST);
	die();
	
  
	
}


/*  直接支付订单 */
elseif($action== 'dones'){
	
	include_once('includes/cls_json.php');
	include_once(ROOT_PATH .'includes/lib_clips.php');
	include_once('includes/lib_payment.php');
	$user = get_user_default($_SESSION['user_id']);
    $_POST['arr']=strip_tags(urldecode($_POST['arr']));
    $_POST['arr'] = json_str_iconv($_POST['arr']);
	$json  = new JSON;
	$arr = $json->decode($_POST['arr']);
	$result = array('error' => 0, 'message' => '', 'content' => '', 'goods_id' => '');
	$order = get_sheep_info($arr->order_id);
	$order_id = $arr->order_id;
	if(empty($order)){
		$result['error'] = 2;
		$result['message'] = "该订单已过期,请重新下单";
		die($json->encode($result));
	}
	
	
	$pays = $GLOBALS['db']->getRow("select * from ". $GLOBALS['ecs']->table('payment') ." where pay_code = '". $arr->code ."'");
	if(empty($pays)){
		$result['error'] = 2;
		$result['message'] = "没有该支付方式，请联系管理员";
		die($json->encode($result));
	}
	if($_SESSION['user_id'] <= 0){
		$result['error'] = 1;
		$result['message'] = "用户登录超时";
        die($json->encode($result));
	}
	
	
	$userset = get_user_set($_SESSION['user_id']);
	/* 如果是是余额支付 */ 
	if($arr->code  == 'balance' && !empty($arr->pay_password) && $arr->cart_id > 0 ){
		/* 验证 密码是否正确 */
		if($user['pay_password'] != $arr->pay_password ||  empty($arr->pay_password)){
			$result['error'] = 2;
			$result['message'] = "支付密码不对,重新输入";
			die($json->encode($result));
		}
		/* 验证 当前用户钱是否够 */
		if($user['user_money'] < $sheep_cart['sheep_price']){
			$result['error'] = 2;
			$result['message'] = "青山羊币不足,请充值或者用认证银行卡支付";
			die($json->encode($result));
		}
	}
	/* wk  如果是微信支付 */
	if($arr->code  == 'wxpay'){
		$return_url = 'http://' . $_SERVER['HTTP_HOST'].'/respond.php&code=wxpay';
		$payment = unserialize($pays['pay_config']);
		define (WXAPPID, $payment['0']['value']); // appid
		define (WXAPPSECRET, $payment['1']['value']); // appSecret
		define (WXMCHID, $payment['2']['value']);
		define (WXKEY, $payment['3']['value']); // 通加密串
		define (NOTIFY_URL, $return_url); // 成功回调url
		include_once("includes/modules/payment/WxPayPubHelper/WxPayPubHelper.php");
		$jsApi = new JsApi_pub();
		$selfUrl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'];
		if($_SESSION['user_id']){
			$openid = $GLOBALS['db']->getOne("select wxid from ". $GLOBALS['ecs']->table('users') ." where user_id ='{$_SESSION['user_id']}'");
		}
		$openid = $openid ? $openid : $_SESSION['openids'];
		if(empty($openid)){
			$result['error'] = 2;
			$result['message'] = "当前用户没有绑定微信,请在微信端打开进行支付";
			die($json->encode($result));
		}
	}
	
	
	/*  余额支付  处理后续操作 */
	if($arr->code  == 'balance'){
		/* 购买通知  */
		$order['order_id'] = $order_id;
		if($userset['wxid'] && $userset['yz_gm_msg'] == 1){
			wx_msg($userset['wxid'],3,$order);
		}
		
		/* 给上级 发送信息 */
		if($userset['parent_id'] > 0){
			$u_set = get_user_set($userset['parent_id']);
			if($u_set['wxid'] && $userset['tg_gm_msg'] == 1){
				wx_msg($u_set['wxid'],5,$order);
			}
		}
		$sql = "UPDATE ". $ecs->table('sheep_order') ." SET pay_time = '". gmtime() ."' , state = '2',pay_type = 'balance' WHERE order_id= '". $order_id ."'";
        $db->query($sql);
		/* 根据订单ID 生成排队分成队列 */
		bonus_queue($order_id);
		/* 扣钱 */
		$text = "购买羊支出青山羊币：".$sheep_cart['sheep_price'];
		log_account_change($_SESSION['user_id'], -$sheep_cart['sheep_price'], 0, 0, 0, $text , ACT_GMY); // 购买羊
		$result['order_id'] = $order_id;
		$result['error'] = 0;
		$result['message'] = "购买成功";
		die($json->encode($result));
	}
	
	/* 微信支付 */
	if($arr->code  == 'wxpay'){
		/* 购买通知  */
		$order['order_id'] = $order_id;
		// if($userset['wxid'] && $userset['yz_gm_msg'] == 1){
			// wx_msg($userset['wxid'],3,$order);
		// }		
		$unifiedOrder = new UnifiedOrder_pub();
		// 设置统一支付接口参数
		$unifiedOrder->setParameter ( "openid", $openid );
		$unifiedOrder->setParameter ( "body", 'GMYZ' );
		$unifiedOrder->setParameter ( "out_trade_no", $order['order_id'] ); // 商户订单号
		$unifiedOrder->setParameter ( "total_fee", $order['sheep_price'] * 100 ); // 总金额
		$unifiedOrder->setParameter ( "notify_url", NOTIFY_URL ); // 通知地址
		$unifiedOrder->setParameter ( "trade_type", "JSAPI" ); // 交易类型
	
		$prepay_id = $unifiedOrder->getPrepayId();
		$jsApi->setPrepayId($prepay_id);
		$obj['appId'] = $result['appId2'] = $payment['0']['value'];
		$obj['timeStamp'] = $result['timeStamp'] = time();
		$obj['nonceStr'] = $result['nonceStr2'] = $unifiedOrder->createNoncestr();
		$obj['package'] = $result['packages'] = "prepay_id=".$jsApi->prepay_id;
		$obj['signType'] = $result['signType2'] = 'MD5';
		$result['paySign2'] = $unifiedOrder->getSign($obj);
		$result['message'] = 'success';
		$result['order_id'] = $order_id;
		$result['error'] = 20;
		die($json->encode($result));

	}
	
	
	
		/* 如果是其他支付 */
	if($arr->code  != 'balance' &&  !empty($arr->code) && $arr->code  != 'wxpay'){
		
		$payment = $GLOBALS['db']->getRow("select * from ". $GLOBALS['ecs']->table('payment') ." where pay_code = '". $arr->code ."'");
		if(empty($payment)){
			$result['error'] = 0;
			$result['message'] = "没有该支付方式，请联系管理员";
			die($json->encode($result));
		}

		$order['order_id'] = $order_id;

        include_once('includes/modules/payment/' . $payment['pay_code'] . '.php');
        $pay_obj    = new $payment['pay_code'];
		// $order['order_id'] = '1'; /* 后期用订单 id  */
		
		$order['order_amount'] = $order['sheep_price'];/* 总金额 */
		// $order['order_amount'] = '0.01';/* 总金额 */
		
		$order['log_id'] = insert_pay_log($order['order_id'], $order['order_amount'], PAY_YZGM); /* 羊只付款 */
		// $order['order_sn'] = gmtime().'GMYZ';/* 回调准备才分 */
		$order['order_sn'] = 'SLYDDHGM'.$order['log_id'];/* 回调准备才分 */

		
		$sql = "UPDATE ". $ecs->table('sheep_order') ." SET order_sn = '". $order['order_sn'] ."'  WHERE order_id= '". $order_id ."'";
        $db->query($sql);
		
        $pay_online = $pay_obj->get_code($order, unserialize_config($payment['pay_config']));
        // $order['pay_desc'] = $payment['pay_desc'];
		// $smarty->assign('pay_online', $pay_online);
		$result['error'] = 10;
		$result['message'] = "支付按钮";
		$result['pay_online'] =  $pay_online;
		die($json->encode($result));
		
	}
	
	
	
	
	
	
	
	
	echo "<pre>"; print_r($arr);die();
	
}	
	
/*  ajax  更新订单数据 */
elseif($action== 'ajax_gengxin'){
	include_once('includes/cls_json.php');
	include_once(ROOT_PATH .'includes/lib_clips.php');
	include_once('includes/lib_payment.php');
	$user = get_user_default($_SESSION['user_id']);
    $_POST['arr']=strip_tags(urldecode($_POST['arr']));
    $_POST['arr'] = json_str_iconv($_POST['arr']);
	$json  = new JSON;
	$arr = $json->decode($_POST['arr']);
	$result = array('error' => 0, 'message' => '', 'content' => '');
	
	$order_id = intval($arr->order_id) ;
	$order =  $GLOBALS['db']->getRow("select * from ". $GLOBALS['ecs']->table('sheep_order') ." where order_id = '". $order_id ."'");
	if($order){
		$result['error'] = 2;
		$result['message'] = "无效订单";
		die($json->encode($result));
	}
	
	$userset = get_user_set($order['user_id']);
	/* 购买通知  */
	$order['order_id'] = $order_id;
	if($userset['wxid'] && $userset['yz_gm_msg'] == 1){
		wx_msg($userset['wxid'],3,$order);
	}	
		
	/* 给上级 发送信息 */
	if($userset['parent_id'] > 0){
		$u_set = get_user_set($userset['parent_id']);
		if($u_set['wxid'] && $userset['tg_gm_msg'] == 1){
			wx_msg($u_set['wxid'],5,$order);
		}
	}
	/* 根据订单ID 生成排队分成队列 */
	bonus_queue($order_id);

	$sql = "UPDATE ". $ecs->table('sheep_order') ." SET pay_time = '". gmtime() ."',pay_type = 'wxpay' WHERE order_id= '". $order_id ."'";
    $db->query($sql);
	/* 记录 羊被购买的字段 */
	updata_sheep($order['sheep_id'],$order['sheep_number']);
	
	$result['order_id'] = $order_id;
	$result['error'] = 0;
	$result['message'] = "购买成功";
	die($json->encode($result));
	
	
}




/*  显示订单支付结果*/
elseif($action== 'pay_result'){
	
	$order_id  = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : '';
	weizhfu_order();
	$smarty->assign('acts',        'sheep');
	$smarty->assign('page_title',        '羊只列表');

	$order = get_sheep_info($order_id);
    include_once(ROOT_PATH .'includes/lib_clips.php');
	
	$info = get_user_default($_SESSION['user_id']);
	$smarty->assign('info',        $info);
 
	if($order['user_id'] != $_SESSION['user_id']){
		show_message("不能操作别人的订单", "返回上一页", 'sheep.php', 'error');
	}
	
	$pay_name = $db->getOne("select pay_name from ". $ecs->table('payment') ." where pay_code = '". $order['pay_type'] ."'" );
	if(empty($pay_name)){
		$pay_name = '微信支付';
	}
	$smarty->assign('pay_name',        $pay_name);
	
	$smarty->assign('order',        $order);
	$smarty->display('pay_result.dwt');
}

















?>